<?php
    //класс для работы с базами данных. 

    class db {
        static $query_counts = 0;
        static $link;
        static $server = 'localhost';
        static $username = '';
        static $password = '';
        static $base = '';
        //подключаемся к базе
        public static function connect() 
        {
            if ( empty(self::$password) and empty(self::$password))
            {
                $conf = m::json_data_read('conf.dat');

                self::$server = $conf['db_server'];
                self::$username = $conf['db_username'];
                self::$password = $conf['db_password'];
                self::$base = $conf['db_base'];
            }
            
            self::$link = @mysql_connect(self::$server, self::$username, self::$password, self::$link); 

            if ( self::$link )
            {
                @ mysql_select_db( self::$base );
                mysql_set_charset("utf8",self::$link);
                @ mysql_query("SET NAMES 'utf8' COLLATE 'utf8_general_ci;'");
            }

            if ( !self::$link ) 
            {
                self::error("connect", mysql_errno(), mysql_error());
            }

            return true;
        }

        //выполняет запрос к бд
        public static function query($query) 
        {
            self::$query_counts++; 

            $result = mysql_query($query) or self::error($query, mysql_errno(), mysql_error());

            if ( !$result ) 
            {
                self::error($query, mysql_errno(), mysql_error());
            }

            return $result;
        }

        public static function fetch_array(&$db_query,$cq=false)
        {
            if (is_array($db_query)) 
            {
                $curr = current($db_query);
                next($db_query);
                return $curr;
            }

            return @mysql_fetch_array($db_query, MYSQL_ASSOC);

        }

        public static function error($query, $errno, $error) 
        {
            $log = date("d/m/Y H:m:s",time()) . ' | ' . $errno . ' - ' . $error . ' | ' . $query . ' | ' . $_SERVER["REQUEST_URI"] . "\n";

            echo '<textarea class="round" style="color:red;width:100%; height:100px;">'.$log.'</textarea>';
        }

        public static function input_array($array)
        {
            if ( is_array($array) )
            {
                $array2 = array(); 
                foreach ($array as $name => $value )
                {
                    $array2[ $name ]  = db::input( $value ); 
                } 
                return $array2;
            }
            else
            {
                return false;
            }
        }

        public static function input( $string = '' ) 
        {
            if ( empty($string) ) return '';

            if (function_exists('mysql_real_escape_string')) 
            {
                return mysql_real_escape_string($string);
            } 
            elseif (function_exists('mysql_escape_string')) 
            {
                return mysql_escape_string($string);
            }

            return addslashes($string);
        }

        public static function prepare_input($string) 
        {
            if (is_string($string)) 
            {
                return trim(stripslashes($string));
            } 
            elseif (is_array($string)) 
            {
                reset($string);
                while (list($key, $value) = each($string)) 
                {
                    $string[$key] = $this->prepare_input($value);
                }
                return $string;
            } 
            else 
            {
                return $string;
            }
        }

        public static function data_seek($db_query, $row_number,$cq=false) 
        {
            if (!is_array($db_query)) return mysql_data_seek($db_query, $row_number);
        }

        //закрываем соединение
        public static function close() 
        {
            //если постоянное подключение не вклюено - тогда закрывать соединение
            //if ( USE_PCONNECT == false)
            // {
            // return 
            mysql_close( self::$link );  
            //} 
        }

        public static function insert_id() 
        {
            return mysql_insert_id();
        }

        public static function output($string) 
        {
            return htmlspecialchars($string);
        }

        public static function select_db($database) 
        {
            return mysql_select_db($database);
        }

        public static function fetch_fields($db_query) 
        {
            return mysql_fetch_field($db_query);
        }

        public static function num_rows($db_query, $cq=false) 
        {
            if ( !is_array($db_query) ) return mysql_num_rows($db_query);
        }

        //получает количество рядов, задействованных в предыдущей MySQL-операции.
        public static function affected_rows()
        {
            return mysql_affected_rows ();
        }

        public static function perform($table, $data, $action = 'insert', $parameters = '', $link = 'db_link') 
        {
            reset($data);

            if ($action == 'insert') 
            {
                $query = 'insert into ' . $table . ' (';
                while (list($columns, ) = each($data)) 
                {
                    $query .= $columns . ', ';
                }

                $query = substr($query, 0, -2) . ') values (';
                reset($data);

                while (list(, $value) = each($data)) 
                {
                    $value = (is_Float($value) ) ? sprintf("%.F",$value) : (string)($value);
                    switch ($value) 
                    {
                        case 'now()':
                            $query .= 'now(), ';
                            break;
                        case 'null':
                            $query .= 'null, ';
                            break;
                        default:
                            $query .= '\'' . db::input($value) . '\', ';
                            break;
                    }
                }
                $query = substr($query, 0, -2) . ')';
            } 
            elseif ($action == 'update') 
            {
                $query = 'update ' . $table . ' set ';
                while (list($columns, $value) = each($data)) 
                {
                    $value = (is_Float($value) ) ? sprintf("%.F",$value) : (string)($value);
                    switch ($value) 
                    {
                        case 'now()':
                            $query .= $columns . ' = now(), ';
                            break;
                        case 'null':
                            $query .= $columns .= ' = null, ';
                            break;
                        default:
                            $query .= $columns . ' = \'' . db::input($value) . '\', ';
                            break;
                    }
                }
                $query = substr($query, 0, -2) . ' where ' . $parameters;
            }

            return self::query($query, $link);
        }

    }
?>